package com.cameron.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cameron.entity.BackendMemberDto;
import com.cameron.entity.CourseVo;
import com.cameron.servicebase.config.exception.BusinessException;
import com.cameron.ucenter.client.CourseClient;
import com.cameron.entity.UcenterMember;
import com.cameron.ucenter.entity.vo.*;
import com.cameron.ucenter.mapper.UcenterMemberMapper;
import com.cameron.ucenter.service.UcenterMemberService;
import com.cameron.utils.*;
import com.hooper.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.cameron.constant.RoleConstant.*;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author cameron
 * @since 2022-06-30
 */
@Service
@Slf4j
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private CourseClient courseClient;


    @Override
    public Result login(UcenterMember member) {
        String phone = member.getMobile();
        String password = member.getPassword();
        //判断用户是否输入
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(phone)) {
            return Result.error().message("手机号或密码为空！");
        }
        if (phone.length() != 11) return Result.error().message("请输入正确的手机号！");
        //判断用户是否存在
        LambdaQueryWrapper<UcenterMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UcenterMember::getMobile, phone);
        UcenterMember user = this.getOne(lqw);
        if (user == null) {
            return Result.error().message("没有该用户，请先注册！");
        }
        //判断密码是否正确
        password = MD5.encrypt(password);
        if (!user.getPassword().equals(password)) {
            return Result.error().message("密码错误！");
        }
        //登录成功则生成token
        String token = JwtUtils.getJwtToken(user.getId(), user.getNickname());
        log.info(token);
        return Result.ok().data("token", token);
    }

    @Override
    public Result register(RegisterVo registerVo) {
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();
        if (StringUtils.isEmpty(nickname) || StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)) {
            return Result.error().message("请填写所有信息！");
        }
        if (mobile.length() != 11) return Result.error().message("请输入正确的手机号！");
        String cacheCode = redisTemplate.opsForValue().get(mobile);
        log.info("用户中心获取到验证码:{}", cacheCode);
        if (!code.equals(cacheCode)) {
            return Result.error().message("验证码错误！");
        }
        LambdaQueryWrapper<UcenterMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UcenterMember::getMobile, mobile);
        int count = this.count(lqw);
        if (count > 0) {
            return Result.error().message("用户已存在！");
        }
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setNickname(nickname);
        ucenterMember.setMobile(mobile);
        password = MD5.encrypt(password);
        ucenterMember.setPassword(password);
        //make the user usable
        ucenterMember.setIsDisabled(false);
        //设置随机默认头像
        ucenterMember.setAvatar("https://cam-guliedu.oss-cn-beijing.aliyuncs.com/radom-avatar/avatar/" + (RandomUtil.randomInt(100) + 1) + ".png");
        return this.save(ucenterMember) ? Result.ok() : Result.error().message("未知错误！");
    }

    @Override
    public UcenterMember getByOpenid(String openid) {
        if (StringUtils.isEmpty(openid)) {
            return null;
        }
        LambdaQueryWrapper<UcenterMember> lqw = new LambdaQueryWrapper<>();

        lqw.eq(UcenterMember::getOpenid, openid);

        return this.getOne(lqw);
    }

    @Override
    public Integer countRegister(String date) {
        log.info("收到date:{}", date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //若传入的日期格式不正确则返回-1
            simpleDateFormat.parse(date);
        } catch (ParseException e) {
            log.error("日期格式错误！\n" + e.getMessage());
            return -1;
        }
        return baseMapper.getRegisterCount(date);
    }

    @Override
    public AboutMeVo getAboutMe(String memberId) {
        UcenterMember member = this.getById(memberId);
        AboutMeVo aboutMeVo = new AboutMeVo();
        aboutMeVo.setMemberId(memberId);
        aboutMeVo.setAvatar(member.getAvatar());
        aboutMeVo.setNickname(member.getNickname());
        aboutMeVo.setRole(member.getMemberRoles());
        aboutMeVo.setSex(member.getSex() == 1 ? "女" : "男");
        aboutMeVo.setAge(member.getAge() == null ? -1 : member.getAge());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        aboutMeVo.setRegisterTime(dateFormat.format(member.getGmtCreate()));
        List<CourseVo> collectList = courseClient.getCollectListByMemberId(memberId);
        aboutMeVo.setCollectList(collectList);
        return aboutMeVo;
    }

    @Override
    public BackendMemberDto backendLogin(String mobile, String password) {
        if (StringUtils.isAnyBlank(mobile, password)) {
            throw new BusinessException(40005, "账号或密码为空！");
        }
        LambdaQueryWrapper<UcenterMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UcenterMember::getMobile, mobile)
                .eq(UcenterMember::getPassword, MD5.encrypt(password));
        UcenterMember member = this.getOne(wrapper);
        if (member == null)
            throw new BusinessException(40004, "用户不存在");
        int role = member.getMemberRoles();
        if (role != MEMBER_ADMIN && role != MEMBER_TEACHER)
            throw new BusinessException(40003, "无权限！");
        BackendMemberDto memberDto = new BackendMemberDto();
        memberDto.setName(member.getNickname());
        memberDto.setAvatar(member.getAvatar());
        memberDto.setId(member.getId());
        memberDto.setRoles(role);
        //返回当前用户登录的角色信息
        return memberDto;
    }
}
